package com.my.lucky.util;

import lombok.extern.slf4j.Slf4j;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

@Slf4j
public class WenTest {
    private ScriptEngine engine;
    //   private static final String JS_PATH = "D:\\workspace\\workot\\lucky\\src\\main\\java\\com\\my\\lucky\\util\\wen.js";

    public WenTest() {
        try {
            // 初始化JavaScript引擎
            ScriptEngineManager manager = new ScriptEngineManager();
            engine = manager.getEngineByName("nashorn");

            // 添加必要的JavaScript环境
            engine.eval("var console = {" +
                    "log: function(msg) { print(msg); }," +
                    "warn: function(msg) { print('WARN: ' + msg); }," +
                    "error: function(msg) { print('ERROR: ' + msg); }," +
                    "info: function(msg) { print('INFO: ' + msg); }" +
                    "};");

            // 添加其他必要的全局变量
            engine.eval("var window = {};");
            engine.eval("var document = {};");

            // 添加必要的浏览器环境变量
            engine.eval("var navigator = {" +
                    "userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'," +
                    "appName: 'Netscape'," +
                    "appVersion: '5.0'," +
                    "platform: 'Win32'" +
                    "};");

            // 读取并执行JS文件
            URL resourceUrl = WenTest.class.getClassLoader().getResource("static/js/wen.js");
            if (resourceUrl == null) {
                throw new RuntimeException("无法找到资源文件: js/wen.js");
            }

            String filePath;
            try {
                filePath = URLDecoder.decode(resourceUrl.getPath(), StandardCharsets.UTF_8.name());
                // 如果是Windows系统，去掉路径开头的'/'
                if (System.getProperty("os.name").toLowerCase().contains("win")) {
                    filePath = filePath.startsWith("/") ? filePath.substring(1) : filePath;
                }
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException("解码文件路径失败", e);
            }

            log.info("资源文件路径: {}", filePath);
            File jsFile = new File(filePath);

            engine.eval(new FileReader(jsFile));

            // 初始化必要的变量
            engine.eval("var TOKEN_SERVER_TIME = Math.floor(Date.now() / 1000);");

        } catch (ScriptException | IOException e) {
            throw new RuntimeException("初始化JS引擎失败: " + e.getMessage(), e);
        }
    }

    public static void main(String[] args) {
        WenTest wenTest = new WenTest();
        // 使用当前时间戳作为服务器时间
        long serverTime = System.currentTimeMillis() / 1000;
        String token = wenTest.getToken(serverTime);
        log.info("生成的Token: {}", token);
    }

    public String getToken(long serverTime) {
        try {
            // 设置服务器时间
            engine.eval("TOKEN_SERVER_TIME = " + serverTime);

            // 调用rt.update()函数
            Object result = engine.eval("rt.update()");
            return result != null ? result.toString() : null;
        } catch (ScriptException e) {
            log.info("错误详情: {}", e.getMessage());
            throw new RuntimeException("执行JS代码失败: " + e.getMessage(), e);
        }
    }
} 